package JasPerl::Util::Boolean;

use strict;
use warnings;

use parent qw(Exporter);

use JasPerl::Util::Exceptions;
use Scalar::Util qw(blessed);

our @EXPORT_OK = qw(TRUE FALSE);

sub new {
    my ($class, $value) = @_;
    bless \$value, $class;
}

sub parse {
    my ($class, $s) = @_;
    my $value = $s && lc($s) ne 'false';
    return $value ? $class->TRUE : $class->FALSE;
}

sub from {
    my ($class, $from) = @_;
    return $class->FALSE unless defined $from;
    return $class->parse($from) unless ref $from;

    if (blessed $from) {
        return $from if $from->isa($class);
    }

    JasPerl::Util::CoercionException->throw(
        "Cannot create $class from " . (ref $from || 'scalar')
    );
}

sub value {
    return ${$_[0]};
}

sub as_string {
    return $_[0]->value ? 'true' : 'false';
}

use overload (
    bool => 'value',
    '""' => 'as_string'
);

use constant TRUE => JasPerl::Util::Boolean->new(1);

use constant FALSE => JasPerl::Util::Boolean->new(0);

# sub TRUE {
#     # a blessed "constant"
#     state $const = JasPerl::Util::Boolean->new(1);
#     return $const;
# }
# 
# sub FALSE {
#     # a blessed "constant"
#     state $const = JasPerl::Util::Boolean->new(0);
#     return $const;
# }

1;
